<template>
  <el-dialog
    top="10vh"
    width="900px"
    title="价格明细"
    :visible.sync="dialogValue"
    :close-on-click-modal="false"
    append-to-body
  >
    <div style="display: flex;justify-content: flex-end;margin-bottom: 12px">
      <el-button type="primary" @click="onAdd">添加</el-button>
    </div>
    <div class="table-layout">
      <el-table
          size="large"
          stripe
          border
          v-loading="loading"
          max-height="500px"
          :data="priceList"
          row-key="id"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(255, 255, 255, 0.8)"
      >
        <el-table-column align="center" label="规则类型" prop="ruleType" width="120px">
          <template slot-scope="scope">
            <el-select v-model="scope.row.ruleType" placeholder="请选择" style="width: 80px">
              <el-option label="尖" value="0" />
              <el-option label="峰" value="1" />
              <el-option label="平" value="2" />
              <el-option label="谷" value="3" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="单价" prop="chargingPrice">
          <template slot-scope="scope">
            <el-input-number  style="width: 120px" v-model="scope.row.chargingPrice" controls-position="right" :step="0.001" :min="0.001"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" label="服务费" prop="serviceMoney">
          <template slot-scope="scope">
            <el-input-number style="width: 120px" v-model="scope.row.serviceMoney" controls-position="right" :step="0.001" :min="0.001"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" label="时间段" width="300px">
          <template slot-scope="scope">
            <el-time-picker value-format="HH:mm" format="HH:mm" style="width: 120px;margin-right: 5px" v-model="scope.row.startTime"></el-time-picker>
            <el-time-picker value-format="HH:mm" format="HH:mm" style="width: 120px;margin-right: 5px" v-model="scope.row.endTime"></el-time-picker>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="100px">
          <template slot-scope="scope">
            <el-button type="text" @click="onSave(scope.row)">{{ scope.row.id ? '更新' : '保存'}}</el-button>
            <el-button type="text" style="color: #F82222" @click="onDelete(scope.row, scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-dialog>
</template>

<script>
import { http } from '@/api'
export default {
  name: 'FormAdd',
  data() {
    return {
      apiKey: 'price',
      dialogValue: false,
      loading: false,
      priceList: [
      ],
      ruleId: ''
    }
  },
  methods: {
    open(row) {
      this.ruleId = row.id
      this.dialogValue = true
      if (row) {
        this.getPriceList()
      }
    },
    getPriceList() {
      this.loading = true
      http[this.apiKey].list({
        ruleId:this.ruleId
      }).then(res => {
        this.priceList = res.data
      }).finally(() => {
        this.loading = false
      })
    },
    onAdd() {
      this.priceList.push({
        id: undefined,
        ruleType: '0',
        startTime: '00:00',
        endTime: '24:00',
        serviceMoney: 0,
        chargingPrice: 0
      })
    },
    // 检查时间段是否有冲突
    checkTimeConflict(currentRow) {
      const convertTimeToMinutes = (time) => {
        const [hours, minutes] = time.split(':').map(Number);
        return hours * 60 + minutes;
      };

      const currentStart = convertTimeToMinutes(currentRow.startTime);
      const currentEnd = convertTimeToMinutes(currentRow.endTime);

      return this.priceList.filter(item => item.id).some(row => {
        // 跳过当前编辑的行
        if (row.id === currentRow.id) {
          return false;
        }

        const rowStart = convertTimeToMinutes(row.startTime);
        const rowEnd = convertTimeToMinutes(row.endTime);

        // 检查是否有重叠
        return (currentStart < rowEnd && currentEnd > rowStart);
      });
    },
    onSave(row) {
      if (!this.ruleId) {
        return;
      }

      // 验证必填字段
      if (!row.startTime || !row.endTime || !row.chargingPrice || !row.serviceMoney) {
        this.$message.error('请填写完整信息');
        return;
      }

      // 验证时间格式
      if (row.startTime >= row.endTime) {
        this.$message.error('结束时间必须大于开始时间');
        return;
      }

      // 检查时间冲突
      if (this.checkTimeConflict(row)) {
        this.$message.error('当前时间段与已有时间段存在冲突，请调整');
        return;
      }

      http.price[row.id ? 'update' : 'create'](undefined, {
        ...row,
        ruleId: this.ruleId
      }).then(res => {
        this.$message.success('操作成功');
        this.getPriceList();
      });
    },
    onDelete(row,index) {
      if (!row.id) {
        this.priceList.splice(index, 1)
        return
      }
      this.$confirm('确认删除？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(() => {
            http.price.delete(row.id).then(res => {
              this.$message.success('删除成功')
              this.priceList.splice(index, 1)
            })
          })
    },
  }
}
</script>

<style scoped lang="scss">
</style>
